package com.leetao.dingtalk.core.manager;

import com.leetao.dingtalk.core.domain.Token;
import com.leetao.dingtalk.core.domain.rest.Rest;
import com.leetao.dingtalk.core.service.DingTalkAuthService;
import com.taobao.api.ApiException;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * token管理器
 * @author 菅江晖
 * @date 2021/5/24 - 15:08
 */
public class DingTalkTokenManager {
    final private DingTalkAuthService dingTalkAuthService;

    private Token TokenCache;

    @Scheduled(fixedRate = (1000 * 60 * 60 * 2) - (1000*60*20))
    public void clearToken() {
        TokenCache = null;
    }



    public DingTalkTokenManager(DingTalkAuthService dingTalkAuthService) {
        this.dingTalkAuthService = dingTalkAuthService;
    }

    public Rest<Token> getTokenRest() throws ApiException {
        //TODO: 缓存实现
        if (TokenCache != null) {
            return Rest.success("存在缓存", TokenCache);
        }

        Rest<Token> tokenRest = dingTalkAuthService.getToken();
        TokenCache = tokenRest.getData();
        return tokenRest;
    }
}
